﻿using AIStudio.Core.Models;
using AIStudio.Wpf.Business.IBussiness;
using AIStudio.Wpf.Service.AppClient.HttpClients;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AIStudio.Wpf.Business.Bussiness
{
    public class ApiDataProvider : IDataProvider
    {
        private string Url { get; set; }
        public string Token { get; set; }

        public Dictionary<string, string> SetHeader()
        {
            Dictionary<string, string> header = new Dictionary<string, string>();
            header.Add("Authorization", string.Format("Bearer {0}", Token));

            return header;
        }

        public async Task<AjaxResult<T>> GetData<T>(string url, string json = "{}")
        {
            if (!url.StartsWith("http"))
            {
                url = Url + url;
            }
            var content = await HttpClientHelper.Instance.PostAsyncJson(url, json, SetHeader());
            var result = JsonConvert.DeserializeObject<AjaxResult<T>>(content);
            return result;
        }

        public async Task<AjaxResult> GetToken(string url, string userName, string password)
        {
            Url = url;

            var content = await HttpClientHelper.Instance.PostAsyncJson((string.Format("{0}/Base_Manage/Home/SubmitLogin", Url)), JsonConvert.SerializeObject(new { userName = userName, password = password }));
            var result = JsonConvert.DeserializeObject<AjaxResult>(content);
            Token = result.Data as string;

            return result;
        }

    }
}
